package com.example.musicplayer.activity;

import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;

import com.example.musicplayer.MusicScoreManager;
import com.example.musicplayer.R;
import com.example.musicplayer.commonUtils.DrawUtil;
import com.example.musicplayer.dialogTools.EditMusicScoreDialog;
import com.example.musicplayer.musicClass.MusicInfo;
import com.example.musicplayer.musicTools.Lyric;
import com.example.musicplayer.musicTools.MusicListType;
import com.example.musicplayer.service.MusicService;

import java.util.ArrayList;
import java.util.List;

public class MusicDetailsActivity extends ImmersiveActivity {
    public static final int RESULT_CODE = 900;
    public static final String EDIT_MUSIC_SCORE = "scoreChanged";
    private Lyric.MusicDetailInfo mMusicDetailInfo;
    private MusicService.MusicBinder mMusicBinder;
    private boolean mHasStartMusic = false;
    private boolean mEditMusicScore = false;
    private int mMusicId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_details);
        initView();
        mMusicId = getIntent().getIntExtra("musicId", -1);
        MusicInfo musicInfo = MusicInfo.getMusicInfoById(mMusicId);
        mMusicDetailInfo = Lyric.get(musicInfo);
        mMusicBinder = getMusicServiceBinder();
        update();
        setEnableMusicListener(true);
        registerMusicListener(mMusicBinder);
    }

    @Override
    protected void onResume() {
        super.onResume();
        updateView();
    }

    @Override
    public void onBackPressed() {
        finishActivity();
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finishActivity();
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onMusicPlayStateChanged(MusicInfo musicInfo, boolean isPlaying) {
        updateView();
    }

    private void initView() {
        final Toolbar toolbar = findViewById(R.id.toolbar);
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            fitsStatusBar(toolbar);
        }
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayShowTitleEnabled(false);
        }
        findViewById(R.id.image_play).setOnClickListener(v -> {
            if (mMusicBinder != null) {
                if (mHasStartMusic || (mMusicBinder.getMusicCounts() == 1 && mMusicBinder.getId() == mMusicDetailInfo.mId
                        && mMusicBinder.getMusicListType() == MusicListType.TYPE_OTHER)) {
                    mMusicBinder.changePlayingState();
                } else {
                    MusicInfo musicInfo = MusicInfo.getMusicInfoById(mMusicDetailInfo.mId);
                    if (musicInfo != null) {
                        List<MusicInfo> musicList = new ArrayList<MusicInfo>();
                        musicList.add(musicInfo);
                        mMusicBinder.start(musicList, 0);
                        mHasStartMusic = true;
                    }
                }
            }
            updateView();
        });
        findViewById(R.id.image_pause).setOnClickListener(v -> {
            if (mMusicBinder != null) {
                mMusicBinder.pause();
            }
            updateView();
        });
        findViewById(R.id.edit_music_score).setOnClickListener(v -> {
            showEditMusicScoreDialog();
        });
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            findViewById(R.id.scroll_view).setOnScrollChangeListener(new View.OnScrollChangeListener() {
                @Override
                public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                    if (scrollY > oldScrollY) {
                        toolbar.setVisibility(View.GONE);
                    } else if (scrollY < oldScrollY - 15) {
                        toolbar.setVisibility(View.VISIBLE);
                    }
                }
            });
        }
    }

    private void update() {
        ((TextView) findViewById(R.id.item_title)).setText(mMusicDetailInfo.mTitle);
        ((TextView) findViewById(R.id.item_singer)).setText(mMusicDetailInfo.mSinger);
        ((TextView) findViewById(R.id.item_lyric)).setText(mMusicDetailInfo.mLyric);
        ((TextView) findViewById(R.id.item_compose)).setText(mMusicDetailInfo.mComposed);
        ((TextView) findViewById(R.id.item_arrange)).setText(mMusicDetailInfo.mArranged);
        ((TextView) findViewById(R.id.item_produce)).setText(mMusicDetailInfo.mProduced);
        ((TextView) findViewById(R.id.item_album)).setText(mMusicDetailInfo.mAlbum);
        //add lyrics
        StringBuilder lyrics = new StringBuilder();
        for (int i = 0; i < mMusicDetailInfo.mLyrics.size(); i++) {
            lyrics.append(mMusicDetailInfo.mLyrics.get(i));
            if (i != mMusicDetailInfo.mLyrics.size() - 1) {
                lyrics.append("\n");
            }
        }
        ((TextView) findViewById(R.id.item_lyrics)).setText(lyrics.toString());
        //set image
        MusicInfo musicInfo = MusicInfo.getMusicInfoById(mMusicId);
        Bitmap bitmap = DrawUtil.getDefaultBitmap();
        if (musicInfo != null) {
            bitmap = musicInfo.getBitmap();
        }
        ((ImageView) findViewById(R.id.item_image)).setImageBitmap(bitmap);
        updateMusicScore();
    }

    private void updateMusicScore() {
        MusicScoreManager manager = MusicScoreManager.getInstance();
        if (manager != null) {
            MusicScoreManager.MusicScoreInfo musicScoreInfo = manager.read(mMusicId);
            if (musicScoreInfo != null) {
                ((TextView) findViewById(R.id.score_lyric)).setText(String.valueOf(musicScoreInfo.getLyric()));
                ((TextView) findViewById(R.id.score_melody)).setText(String.valueOf(musicScoreInfo.getMelody()));
                ((TextView) findViewById(R.id.score_arrangement)).setText(String.valueOf(musicScoreInfo.getArrangement()));
                ((TextView) findViewById(R.id.score_favor)).setText(String.valueOf(musicScoreInfo.getFavor()));
                ((TextView) findViewById(R.id.score_final)).setText(String.valueOf(musicScoreInfo.getFinal()));
            }
        }
    }

    private void updateView() {
        if (mMusicBinder != null) {
            boolean showPlaying = mMusicBinder.isPlaying() && mMusicBinder.getId() == mMusicDetailInfo.mId;
            findViewById(R.id.image_play).setVisibility(showPlaying ? View.GONE : View.VISIBLE);
            findViewById(R.id.image_pause).setVisibility(showPlaying ? View.VISIBLE : View.GONE);
        }
    }

    private void showEditMusicScoreDialog() {
        if (MusicScoreManager.getInstance() != null) {
            EditMusicScoreDialog dialog = new EditMusicScoreDialog(this, MusicScoreManager.getInstance().read(mMusicId));
            dialog.setOnDataChangedListener(() -> {
                mEditMusicScore = true;
                updateMusicScore();
            });
            dialog.show();
        }
    }

    private void finishActivity() {
        Intent intent = getIntent();
        intent.putExtra(EDIT_MUSIC_SCORE, mEditMusicScore);
        setResult(RESULT_CODE, intent);
        finish();
        setPendingTransition(R.anim.normal_right_enter, R.anim.normal_right_exit);
    }
}